# -*- coding: utf-8 -*-
# @Time : 2021/5/17 12:12 
# @Author : for 
# @File : __init__.py.py 
# @Motto: good good study,day day up

import os
import sys

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from pathlib import Path

from flask_admin import Admin

WIN = sys.platform.startswith('win')
if WIN:
    prefix = 'sqlite:///'
else:
    prefix = 'sqlite:////'

app = Flask(__name__)
app.debug = True
BASE_DIR = Path(app.root_path).parent
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev')
# app.config['SQLALCHEMY_DATABASE_URI'] = prefix + app.root_path + '/' + os.getenv('DATABASE_FILE', 'data.db')
app.config['SQLALCHEMY_DATABASE_URI'] = prefix + str(BASE_DIR) + '/data.db'
print(app.config['SQLALCHEMY_DATABASE_URI'])
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SECRET_KEY'] = os.urandom(24)
app.config['BABEL_DEFAULT_LOCALE'] = 'zh_CN'
db = SQLAlchemy(app)
login_manager = LoginManager(app)  # 实例化扩展类
admin = Admin(app, name='电影', template_mode='bootstrap3')


@login_manager.user_loader
def load_user(user_id):  # 创建用户加载回调函数，接受用户 ID 作为参数
    from watchlist.models import User
    user = User.query.get(int(user_id))  # 用 ID 作为 User 模型的主键查询对应的用户
    return user  # 返回用户对象


login_manager.login_view = 'login'


@app.context_processor
def inject_user():  # 函数名可以随意修改
    from watchlist.models import User
    user = User.query.first()
    return dict(user=user)  # 需要返回字典，等同于 return {'user': user}


from watchlist import views, errors, commands, bg_admin

# from flask_admin.contrib.sqla import ModelView
# from watchlist.models import User, Movie
#
# admin.add_view(ModelView(User, db.session))
# admin.add_view(ModelView(Movie, db.session))
